import React, { Component } from 'react';
import { routerRedux, Route, Switch } from 'dva/router';

import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import { connect } from 'dva';
import {
    Button, Dropdown, Icon, Row, Col,
    Input, InputNumber,
    Card, Modal,
    message, TreeSelect,
    Form, Upload
} from 'antd';
import classNames from 'classnames';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import DescriptionList from '../../components/DescriptionList';
import styles from './ChannelDetails.less';
import { create } from 'domain';
import { validatemobile } from '../../utils/utils';
import querystring from 'querystring';


const Search = Input.Search;
const FormItem = Form.Item;
const TextArea = Input.TextArea;
const TreeNode = TreeSelect.TreeNode;
const { Description } = DescriptionList;
//渠道维护-详情页面
const getWindowWidth = () => (window.innerWidth || document.documentElement.clientWidth);

export let profileState = false;

@connect(({ channel }) => ({
    channel,
    // loading: loading.effects['applyDetail/fetchAdvanced'],
}))
@Form.create()
export default class ChannelDetails extends Component {
    state = {
        size: 'default',
        user: {
            merchantName: '',
            leader: '',
            phone: '',
            regAddress: '',
        },
        previewImage: '',
        previewVisible: false,
        companyNameInEdit: false,
        headInEdit: false,
        phoneNumberInEdit: false,
        addressInEdit: false,
        id: '',
        channelState: '',
        branchIdList: [],
        fileList: [],
        imageRotateDeg: 0,
        enlarge: 1,
        // imgWidth1: 300,
        // imgHeight1: 600
    } 

    componentDidMount() {
        const { dispatch, location } = this.props;
        const params = querystring.parse(location.search.slice(1));
        this.setState({
            id: params.id,
            channelState: params.state,
        });
        dispatch({
            type: 'channel/details',
            payload: {
                id: params.id,
            },
            callback: () => {
                const { channel: { channel, branchList } } = this.props;
                let branchId = branchList && branchList
                let branchIdArray = this.state.branchIdList
                if (branchList != null) {
                    for (let i = 0; i < branchId.length; i++) {
                        branchIdArray.push(branchId[i].id)
                    }
                }
                let fileList = this.state.fileList;
                // console.log("channel.license", channel)
                channel.license &&
                    fileList.push({
                        uid: channel.license,
                        name: 'xxx.png',
                        status: 'done',
                        url: channel.license,
                    });
                this.setState({
                    fileList: fileList,
                    branchIdList: branchIdArray,
                    user: {
                        ...this.state.user,
                        merchantName: channel.merchantName,
                        leader: channel.leader,
                        phone: channel.phone,
                        regAddress: channel.regAddress
                    }
                })
            }
        });
        dispatch({
            type: 'channel/getBranchTreeList',
        });
    }
    handleSizeChange = (e) => {
        this.setState({ size: e.target.value });
    }

    handleCompanyNameChange = (e) => {
        const value = e.target.value;
        this.setState({
            user: {
                ...this.state.user,
                merchantName: value,
            }
        });
    }

    handleHeadChange = (e) => {
        const value = e.target.value;
        this.setState({
            user: {
                ...this.state.user,
                leader: value,
            }
        });
    }

    handlePhoneNumberChange = (value) => {
        this.setState({
            user: {
                ...this.state.user,
                phone: value,
            }
        });
    }

    hanleClickEdit = () => {
        this.setState({
            companyNameInEdit: true,
            userTemp: this.state.user,
        });
    }

    hanleClickSave = () => {
        let phoneNum = validatemobile(this.state.user.phone)
        if (phoneNum) {
            if (this.state.user.regAddress && this.state.user.phone && this.state.user.leader && this.state.user.merchantName) {
                this.setState({
                    companyNameInEdit: false,
                });
                this.props.dispatch({
                    type: 'channel/changeChannelDetails',
                    payload: {
                        id: this.state.id,
                        merchantName: this.state.user.merchantName,
                        leader: this.state.user.leader,
                        phone: this.state.user.phone,
                        regAddress: this.state.user.regAddress,
                    },
                    callback: () => {
                        this.props.dispatch({
                            type: 'channel/details',
                            payload: {
                                id: this.state.id,
                            },
                        });
                    },
                })
            } else {
                message.warning("请先填写完毕")
            }
        } else {
            message.warning("请输入正确的联系方式")
        }
    }

    hanleClickCancel = () => {
        this.setState({
            companyNameInEdit: false,
            user: {
                ...this.state.user,
                merchantName: this.state.userTemp.merchantName,
                leader: this.state.userTemp.leader,
                phone: this.state.userTemp.phone,
                regAddress: this.state.userTemp.regAddress,
            }
        });
    }


    handleAddressChange = (e) => {
        const value = e.target.value;
        this.setState({
            user: {
                ...this.state.user,
                regAddress: value,
            }
        });
    }

    handleCancel = () => this.setState({ previewVisible: false, enlarge: 1 })

    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
            imageRotateDeg: 0,
        });
    }

    handleChangeFileList = ({ fileList }) => this.setState({ fileList })

    handleRotate = () => {
        this.setState({
            imageRotateDeg: this.state.imageRotateDeg + 90,
            // imgWidth1: 900,
            // imgHeight1: 500
        });
    }
    handleAmplification = () => {
        if (this.state.enlarge >= 2) {
            message.warning("不能再放大了")
        } else {
            this.setState({
                enlarge: this.state.enlarge * 2,
            })
        }
    }
    handleNarrow = () => {
        if (this.state.enlarge <= 1) {
            message.warning("不能再缩小了")
        } else {
            this.setState({
                enlarge: this.state.enlarge * 0.5,
            })
        }
    }

    handleBranchIdList = (value) => {
        this.setState({
            branchIdList: value,
        });
    }

    handleClickSubmit = () => {
        //1是修改  2是激活
        if (this.state.branchIdList.length > 0) {
            this.state.channelState == '1' ?
                this.props.dispatch({
                    type: 'channel/changeChannelDetails',
                    payload: {
                        id: this.state.id,
                        branchIdList: this.state.branchIdList,
                    },
                    callback: () => {
                        this.props.dispatch({
                            type: 'channel/details',
                            payload: {
                                id: this.state.id,
                            },
                        });
                    },
                })
                :
                this.props.dispatch({
                    type: 'channel/changeChannelActivation',
                    payload: {
                        id: this.state.id,
                        state: 1,//只有激活的时候传1，其他是什么状态就传什么状态
                        branchIdList: this.state.branchIdList,
                    },
                    callback: (code) => {
                        if (code == "200") {
                            message.success('激活成功');
                            this.props.dispatch(routerRedux.push('/channel/channel-maintenance'));
                        } else {
                            message.error('激活失败');
                        }
                    },
                })
        } else {
            message.warning("请先选择所属单位")
        }
    }

    renderTreeNodesChildren = (data) => {
        return data.map((item) => {
            if (item.children) {
                return (
                    <TreeNode
                        value={item.id}
                        title={item.orgName}
                        key={item.id}
                        dataRef={item}
                    >
                        {this.renderTreeNodesChildren(item.children)}
                    </TreeNode>
                );
            }
            return <TreeNode
                value={item.id}
                key={item.id}
                dataRef={item}
                title={item.orgName} />;
        });
    }

    render() {
        const { channel: { branchTreeList, branchList, channel, loading } } = this.props;
        const { getFieldDecorator } = this.props.form;
        const { size, channelDetails, channelState } = this.state;
        const { stepDirection, previewVisible, previewImage } = this.state;
        const imgWidth = 500 * this.state.enlarge;
        const imgHeight = 500 * this.state.enlarge;

        return (
            <PageHeaderLayout
                title="基本信息"
                logo={<img alt="" src="https://gw.alipayobjects.com/zos/rmsportal/nxkuOJlFJuAUhzlMTCEe.png" />}
            >
                {/* AAAA{JSON.stringify(branchTreeList)}CCC */}
                <Row>
                    <Col span={24} style={{ border: 1 }}>
                        <Card
                            title={channelState == '1' ? '基本信息修改' : '渠道激活'}
                            bordered={false}
                            loading={loading}
                            style={{ marginBottom: 24 }}
                            extra={
                                this.state.companyNameInEdit ?
                                    <div>
                                        <Button shape="circle" icon="check" onClick={this.hanleClickSave} />
                                        <Button shape="circle" icon="close" style={{ marginLeft: 32 }} onClick={this.hanleClickCancel} />
                                    </div>
                                    :
                                    <a >
                                        <Button shape="circle" icon="form" onClick={this.hanleClickEdit} />
                                    </a>
                            }
                        >
                            <Row>
                                <DescriptionList className={styles.headerList} size="small" col="2">
                                    <Description term="公司名称">
                                        <Row>
                                            <Col span={16}>
                                                {this.state.companyNameInEdit ?
                                                    <Input
                                                        value={this.state.user.merchantName}
                                                        placeholder="请输入"
                                                        onChange={this.handleCompanyNameChange}
                                                        onPressEnter={this.hanleClickSave}
                                                        style={{ width: 260 }}
                                                    />
                                                    :
                                                    this.state.user.merchantName
                                                }
                                            </Col>

                                        </Row>
                                    </Description>
                                    <Description term="登录名">{channel&&channel.merUserName}</Description>

                                </DescriptionList>
                            </Row>
                            <Row style={{ marginTop: 40 }}>
                                <DescriptionList className={styles.headerList} size="small" col="2">
                                    <Description term="负责人">
                                        <Row>
                                            <Col span={16}>
                                                {//this.state.headInEdit ?
                                                    this.state.companyNameInEdit ?
                                                        <Input
                                                            value={this.state.user.leader}
                                                            placeholder="请输入"
                                                            onChange={this.handleHeadChange}
                                                            onPressEnter={this.hanleClickSave}
                                                            style={{ width: 260 }}
                                                        />
                                                        :
                                                        this.state.user.leader
                                                }
                                            </Col>
                                        </Row>

                                    </Description>
                                    <Description term="电话号码">
                                        <Row>
                                            <Col span={16}>
                                                {//this.state.phoneNumberInEdit ?
                                                    this.state.companyNameInEdit ?
                                                        <InputNumber
                                                            value={this.state.user.phone}
                                                            placeholder="请输入"
                                                            onChange={this.handlePhoneNumberChange}
                                                            onPressEnter={this.hanleClickSave}
                                                            style={{ width: 260 }}
                                                        />
                                                        :
                                                        this.state.user.phone
                                                }
                                            </Col>

                                        </Row>
                                    </Description>
                                </DescriptionList>
                            </Row>
                            <Row style={{ marginTop: 40 }}>
                                <DescriptionList className={styles.headerList} size="small" col="2">
                                    <Description term="注册地址">
                                        <Row>
                                            <Col span={16}>
                                                {//this.state.addressInEdit ?
                                                    this.state.companyNameInEdit ?
                                                        <Input
                                                            value={this.state.user.regAddress}
                                                            placeholder="请输入"
                                                            onChange={this.handleAddressChange}
                                                            onPressEnter={this.hanleClickSave}
                                                            style={{ width: 260 }}
                                                        />
                                                        :
                                                        this.state.user.regAddress
                                                }
                                            </Col>
                                        </Row>

                                    </Description>
                                    <Description term="营业执照号">
                                        {channel.licenseNo}
                                    </Description>
                                </DescriptionList>
                            </Row>
                            <Row style={{ marginTop: 40 }}>
                                <DescriptionList className={styles.headerList} size="small" col="2"  >
                                    <Description term="所属单位">
                                        <TreeSelect
                                            style={{ width: '70%' }}
                                            value={this.state.branchIdList}
                                            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                            placeholder="请选择"
                                            allowClear
                                            multiple
                                            treeDefaultExpandAll
                                            onChange={this.handleBranchIdList}
                                        >
                                            {branchTreeList && this.renderTreeNodesChildren(branchTreeList)}
                                        </TreeSelect>
                                    </Description>
                                    <Description term="营业执照">
                                        <div className="clearfix">
                                            <Upload
                                                listType="picture-card"
                                                fileList={this.state.fileList}
                                                onPreview={this.handlePreview}
                                                onChange={this.handleChangeFileList}
                                                showUploadList={{ showRemoveIcon: false }}
                                            >
                                            </Upload>
                                        </div>
                                    </Description>
                                </DescriptionList>

                            </Row>
                            <p style={{ textAlign: 'right', marginTop: 40, marginRight: 50 }}>
                                <Button type="primary" onClick={this.handleClickSubmit}>提交</Button>
                            </p>
                        </Card>

                    </Col>
                    <Modal
                        // width={this.state.imgWidth1}
                        width={imgWidth + 40}
                        // height={this.state.imgHeight1}
                        visible={previewVisible}
                        footer={null}
                        onCancel={this.handleCancel}>
                        <div style={{ justifyContent: 'space-around', display: 'flex' }}>
                            <img alt="example"
                                style={{
                                    width: imgWidth,
                                    height: imgHeight,
                                    transform: `rotate(${this.state.imageRotateDeg}deg)`
                                }}
                                src={previewImage}
                            />
                        </div>
                        <Row type="flex" justify="space-around" style={{
                            marginTop: 25,
                        }} >
                            <Button onClick={this.handleRotate}>旋转</Button>
                            <Button onClick={this.handleAmplification}>放大</Button>
                            <Button onClick={this.handleNarrow}>缩小</Button>
                        </Row>
                    </Modal>
                </Row>
            </PageHeaderLayout>
        );
    }
}
